<?php
/**
 * User: wyman
 * Date: 2020-06-28
 * Email: <yangww@wecut.com>
 */

namespace App\Model;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class AdmModel extends Model
{
    /**
     * @var array 字段配置
     */
    public $columns = [
        'id' => '[ID]|show:1',
    ];

    /**
     * @var array 字段操作
     */
    public $operations = [
        '_action_' => [
            [
                'action' => 'edit',
                'type'   => 'primary',
                'label'  => '编辑',
            ],
            [
                'action' => 'delete',
                'type'   => 'danger',
                'label'  => '删除',
            ],
        ]
    ];

    /**
     * @var array 公共操作
     */
    public $commonOperations = [
        [
            'action' => 'create',
            'type'   => 'success',
            'label'  => '新增',
        ],
    ];

    /**
     * @var array 字段选项
     */
    public $options = [];

    public function getInfo($id)
    {
        $res = $this->newQuery()
            ->where('id', $id)
            ->first();
        return $res ? $res->toArray() : [];
    }

    public function getPageInfo($page, $limit, $params)
    {
        $query = $this->newQuery()
            ->select(array_keys($this->columns));

        $this->addWhere($query);

        $this->handleListParams($query, $params);

        return $this->pageInfo(
            $query,
            $page, $limit);
    }

    public function pageInfo(Builder $query, $page, $limit)
    {
        return [
            'total' => $query->count(),
            'list'  => $query->orderBy($this->primaryKey, 'desc')
                ->forPage($page, $limit)
                ->get()->toArray(),
        ];
    }

    /**
     * 处理列表参数
     * @param Builder $query
     * @param         $params
     * @return Builder
     * @author LiWenYe
     */
    public function handleListParams(Builder &$query, $params)
    {
        // 过滤
        if (!empty($params['filter'])) {
            $filter = json_decode($params['filter'], true);
            foreach ($filter as $field => $value) {
                $explode = explode('[', rtrim($field, ']'));
                empty($explode[1]) && $explode[1] = '=';
                if (is_array($value)) {
                    $query->whereIn($explode[0], $value);
                } else {
                    $query->where($explode[0], $explode[1], $value);
                }
            }
        }

        // 搜索
        if (!empty($params['search'])) {
            $filter = json_decode($params['search'], true);
            $formats = [];
            foreach ($this->commonOperations as $operation) {
                if ($operation['action'] == 'search' && isset($operation['format'])) {
                    $formats[$operation['field']] = $operation['format'];
                }
            }

            foreach ($filter as $field => $value) {
                if (isset($formats[$field])) {
                    $value = str_replace('{value}', $value, $formats[$field]);
                } else {
                    $value = $value . '%';
                }
                $query->where($field, 'like', $value);
            }
        }

        // 排序
        if (isset($params['sort']) && !empty($params['sort'])) {
            $sort = json_decode($params['sort'], true);
            foreach ($sort as $field => $direction) {
                $query->orderBy($field, $direction);
            }
        }

//        // ID处理
//        if (isset($params['id']) && !empty($params['id'])) {
//            $query->where('id', '=', $params['id']);
//        }

        return $query;
    }

    public function addWhere(Builder &$query)
    {
        return $query;
    }
}
